/**
 * 
 */
package com.huarui.desktop.service.impl;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.huarui.desktop.model.ModuleScriptDesc;
import com.huarui.desktop.model.TableMetaData;
import com.huarui.desktop.service.ModuleScriptBuilder;
import com.huarui.desktop.service.ModuleScriptDesigner;
import com.huarui.desktop.service.TableMetaDataService;

/**
 * @author sunpeng
 * 
 */
public class DefaultModuleScriptDesigner implements ModuleScriptDesigner, ApplicationContextAware {

	private ApplicationContext applicationContext;
	private TableMetaDataService tableMetaDataService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.huarui.desktop.service.ModuleScriptDesigner#order(com.huarui.desktop
	 * .service.ModuleScriptBuilder)
	 */
	@Override
	public void order(ModuleScriptDesc desc, ModuleScriptBuilder builder) {
		TableMetaData meta = this.tableMetaDataService.viewTableMetaData(desc.getTableName());
		
		builder.initScript(desc);
		builder.buildSubclass(desc, meta);
		builder.buildFunctInit(meta);
		builder.buildFunctCreate(meta);
		builder.buildFunctOthers(meta);
		
	}

	public void setTableMetaDataService(TableMetaDataService tableMetaDataService) {
		this.tableMetaDataService = tableMetaDataService;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ModuleScriptBuilder getScriptBuilder(String name) {
		if (name == null) {
			Map beans = this.applicationContext.getBeansOfType(ModuleScriptBuilder.class);
			if (beans != null && !beans.isEmpty()) {
				return (ModuleScriptBuilder) beans.values().iterator().next();
			} else {
				return null;
			}
		}
		return (ModuleScriptBuilder) this.applicationContext.getBean(name, ModuleScriptBuilder.class);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;

	}

}
